package cn.xkai.exercise.a;

import com.google.gson.Gson;

/**
 * @description: 旋转数组
 * 自己的思路：暴力双数组截取和拼接
 * 借鉴的思路：多次翻转，1-全翻转，2-k左边翻转，3-k右边翻转
 * 心得：翻转思路想到了，全翻转是代码写错了，没用双指针交换，验证过程中发现不封装reverse函数，存在临时变量left和right耗时会变多
 * @author: kaixiang
 * @date: 2022-06-30
 **/
public class Solution24 {
    public void rotate(int[] nums, int k) {
        int len = nums.length;
        k %= len;
        // 原地翻转
        reverse(nums, 0, len - 1);
        // 左边翻转
        reverse(nums, 0, k - 1);
        // 右边翻转
        reverse(nums, k, len - 1);
    }

    private void reverse(int[] nums, int left, int right) {
        while (left < right) {
            int temp = nums[left];
            nums[left++] = nums[right];
            nums[right--] = temp;
        }
    }

    public void rotateWithArray(int[] nums, int k) {
        int len = nums.length;
        k %= len;
        int[] left = new int[k], right = new int[len - k];
        System.arraycopy(nums, len - k, left, 0, k);
        System.arraycopy(nums, 0, right, 0, len - k);
        System.arraycopy(left, 0, nums, 0, left.length);
        System.arraycopy(right, 0, nums, k, right.length);
    }

    public static void main(String[] args) {
        int[] nums = {-1};
        int k = 4;
        Solution24 solution24 = new Solution24();
        solution24.rotate(nums, k);
        System.out.println(new Gson().toJson(nums));
    }
}
